﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Me.Prettyprint.Cassandra.Utils;
using Me.Prettyprint.Hector.Api.Ddl;

namespace Me.Prettyprint.Cassandra.Serializers
{
    /// <summary>
    /// DateSerializer uses 1970 as start time, since that is what Java and Unix
    /// use for date. Deserializing the date from the bytes always returns UTC time
    /// to keep it simple. Before displaying the date in string format, you will
    /// need to convert it to local time first.
    /// </summary>
    public class DateSerializer : AbstractSerializer<DateTime>
    {
        public static DateSerializer Instance = new DateSerializer();
        public static readonly DateTimeOffset UnixStart = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);

        public DateSerializer()
        {
        }
        public override ComparatorType GetComparatorType()
        {
            return ComparatorType.DATETYPE;
        }
        public override ComparatorType ComparatorType
        {
            get
            {
                return ComparatorType.DATETYPE;
            }
        }
        public static long ToUnixTime(DateTimeOffset dt)
        {
            return Convert.ToInt64(Math.Floor((dt - UnixStart).TotalMilliseconds));
        }
        public static DateTimeOffset FromUnixTime(long ms)
        {
            return UnixStart.AddMilliseconds(ms);
        }
        public override byte[] ToBytes(System.DateTime date)
        {
            byte[] bytes = new byte[0];
            var offset = DateTimeOffset.MinValue;
            offset = new DateTimeOffset(date);
            bytes = ConvertToBigEndianBytes(BitConverter.GetBytes(ToUnixTime(offset)));
            return bytes;
        }
        public override Utils.ByteBuffer ToByteBuffer(DateTime obj)
        {
            return new ByteBuffer(ToBytes(obj));
        }
        /// <summary>
        /// Important note, FromBytes will always return UTC time after it calculates the
        /// time from UnixTime. This means users have to convert it to local time for
        /// display purposes.
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public override System.DateTime FromBytes(byte[] bytes)
        {
            long longtimems = BitConverter.ToInt64(ConvertFromBigEndianBytes(bytes),0);
            DateTimeOffset localtime = FromUnixTime(longtimems);
            return localtime.DateTime;
        }
        public override System.DateTime FromByteBuffer(ByteBuffer buff)
        {
            return FromBytes(buff.GetBuffer());
        }
    }
}
